﻿using System.Collections.Generic;
using EPiServer.Configuration;
using EPiServer.Core;
using EPiServer.SpecializedProperties;
using EPiServer.DataAccess;

namespace EPiSugar.UnitTesting
{
    public class FakeStructureBuilder
    {
        public const string DefaultIntroText = "Lorem ipsum dolor sit amet.";
        public const string DefaultBodyText = "<p>Lorem ipsum dolor sit amet och lite smet.</p>";
                
        private int siteDepth = 3;
        private int siteWidth = 3;

        public FakeStructureBuilder()
        {
        }
        public FakeStructureBuilder(int siteDepth, int siteWidth)
        {
            this.siteDepth = siteDepth;
            this.siteWidth = siteWidth;
        }

        public virtual void Build(PageProviderBase pageProvider)
        {
            PageData rootPage = CreateFakePage(pageProvider, null, PageReference.RootPage, "Root", Fakes.RootPageTypeID, false);
            pageProvider.Save(rootPage, SaveAction.Publish);
            
            PageData wasteBasket = CreateFakePage(pageProvider, PageReference.RootPage, PageReference.WasteBasket, "Wastebasket", Fakes.WastebasketTypeID, false);
            pageProvider.Save(wasteBasket, SaveAction.Publish);

            if (siteDepth > 0)
            {
                PageData startPage = CreateFakePage(pageProvider, PageReference.RootPage, PageReference.StartPage, "Start Page", Fakes.StartPageTypeID, true);
                pageProvider.Save(startPage, SaveAction.Publish);

                AddChildrenTo(pageProvider, PageReference.StartPage, siteDepth - 1, siteWidth);
            }
        }

        protected virtual void AddChildrenTo(PageProviderBase pageProvider, PageReference parentLink, int depth, int width)
        {
            if (depth <= 0)
                return;

            for (int i = 0; i < width; i++)
            {
                var page = CreateFakePage(pageProvider, parentLink, null, "Page " + i, Fakes.NormalPageTypeID, true);
                page["MainIntro"] = DefaultIntroText;
                page["MainBody"] = DefaultBodyText;
                pageProvider.Save(page, SaveAction.Publish);

                AddChildrenTo(pageProvider, page.PageLink, depth - 1, width);
            }
        }

        protected virtual PageData CreateFakePage(PageProviderBase pageProvider, PageReference parentLink, PageReference pageLink, string pageName, int pageTypeID, bool visible)
        {
            var page = pageProvider.GetDefaultPageData(parentLink, pageTypeID, new LanguageSelector("en"));
            if(pageLink != null)
                page.PageLink = pageLink;
            page.PageName = pageName;
            page.VisibleInMenu = visible;
            return page;
        }

    }
}
